﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Configuration;
using System.Threading;

namespace ServidorDeComunicaciones
{
    public class LocalQueue
    {
        string LocalServerName;
        string LocalQueueName;
        string RemoteServerName;
        string RemoteQueueName;
        string IpGestor;

        public LocalQueue()
        {
            LocalServerName = ConfigurationManager.AppSettings["LocalServer"];
            LocalQueueName = ConfigurationManager.AppSettings["LocalQueue"];
            RemoteServerName = ConfigurationManager.AppSettings["RemoteServer"];
            RemoteQueueName = ConfigurationManager.AppSettings["RemoteQueue"];
            IpGestor = ConfigurationManager.AppSettings["IpGestor"];
        }

        public void SendMessage(string label, string mensaje)
        {
            using (var queue = new MessageQueue(@"Formatname:DIRECT=TCP:" + IpGestor + "\\Private$\\" + RemoteQueueName))
            {
                var message = new Message(mensaje);
                message.Label = label;
                message.Formatter = new BinaryMessageFormatter();
                queue.Send(message);
            }
        }

        public void ReceiveMessage()
        {
            while (true)
            {
                string queueName = @LocalServerName + "\\Private$\\" + LocalQueueName;
                if (MessageQueue.Exists(queueName))
                {
                    using (MessageQueue colaLocal = new MessageQueue(queueName))
                    {
                        colaLocal.Formatter = new BinaryMessageFormatter();
                        Message msg = colaLocal.Receive();
                        msg.ToString();
                        Thread HiloAccion = new Thread(AccionMensaje);
                        HiloAccion.Start(msg);
                    }
                }
                else
                {
                    using (MessageQueue colaLocal = MessageQueue.Create(queueName))
                    {
                        colaLocal.Formatter = new BinaryMessageFormatter();
                        Message msg = colaLocal.Receive();
                        msg.ToString();
                        Thread HiloAccion = new Thread(AccionMensaje);
                        HiloAccion.Start(msg);
                    }
                }
            }
        }

        private void AccionMensaje(object mensaje)
        {
            Message Mensaje = (Message)mensaje;
            string Label = Mensaje.Label.ToString();
            string Datos = Mensaje.Body.ToString();
            CommServer.EnviaRespuestaAgente(Label, Datos);
        }
    }
}

